<?php

namespace App\Http\Controllers\Manage;

use App\Helpers\ResponseData;
use App\Helpers\ServiceTrait;
use App\Helpers\Untils;
use App\Http\Controllers\Controller;
use App\Jobs\Finance\ShopReassignBillJob;
use App\Models\CustomerComplaint;
use App\Models\CustomerComplaintRecord;
use App\Models\CustomerManager;
use App\Models\Department;
use App\Models\Shop;
use App\Models\ShopDetail;
use App\Models\ShopKeeperRecord;
use App\Models\ShopRecord;
use App\Models\ShopUpdateHistory;
use App\Models\ShortCutRecord;
use App\Models\SubAccount\SubAccountStaffBind;
use App\Models\SystemUser;
use App\Models\TrainMaterialRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShopController extends Controller
{
    use ResponseData,ServiceTrait,Untils;
    public function shop(Shop $model,Request $request){

        if($request->filled('customer_id')){
            $model = $model->where('customer_id',$request->customer_id);
        }
        $data = $model->with('detail')->orderBy('id','desc')->get();
        return $this->success($data);
    }
    public function list(ShopDetail $model,Request $request){
        $size = $request->input('size',10);
        $user = $request->user();
        if($user->data_permission){
            $model = $this->model($model,$user);
        }
        if($request->filled('customer_id')){
            $model = $model->where('customer_id',$request->customer_id);
        }
        if($request->filled('created_at_start')&&$request->filled('created_at_end')){
            $model = $model->whereBetween('created_at',[$request->created_at_start,$request->created_at_end]);
        }
        if($request->filled('customer_name')){
            $customer = CustomerManager::query()->where('contact_name','like','%'.$request->customer_name.'%')->pluck('id');

            if(count($customer)>0){
                $model = $model->whereIn('customer_id',$customer);
            }
        }
        if($request->filled('company_name')){
            $model = $model->where('shop_name','like','%'.$request->company_name.'%');
        }
        $data = $model->with('shop','customer','department','quotaionInfo')

            ->orderBy('id','desc')->paginate($size);
        return $this->success($data);
    }
    public function store(ShopDetail $model,Request $request){
        $user = $request->user();
        ShopDetail::query()->where('shop_id',$request->shop_id)->first();
        $data = $request->all();
        if(!$request->filled('department_one_id')){

            $data['department_id'] = $user->department_id;
        }else{
            $data['department_id'] = $this->getLastDepartment($request);
        }
        $model->fill($data);
        $model->save();
        return $this->success('保存成功');
    }
    public function edit(ShopDetail $model,Request $request){

        $data = $model
            ->with('shop','customer','department','quotaionInfo.priceRange')
            ->find($request->id);
        return $this->success($data);
    }
    public function update(ShopDetail $model,Request $request){
        $user = $request->user();
        $data = $model->find($request->id);
        $oldDepartmentId=$data->department_two_id;
        $map = $request->except('shop');
        if($request->filled('department_id') && $request->department_id!=$oldDepartmentId){
            //切换部门，原部门立即生成账单
            ShopReassignBillJob::dispatch($data);
            $map['department_three_id']=null;
            $map['reassign_time']=now();
        }

        $data->update($map);

        if($request->filled('department_id') && $request->department_id!=$oldDepartmentId){
            $this->updateSubAccountDepartment($data);
        }
        if($request->filled('shop_materials')){
            $this->setUnreadMessage($request->id,$request->shop_materials,$user,$data);
        }

        return $this->success('修改成功');
    }
   //更新店铺部门id
    public function setShopDepartment(Request $request,ShopDetail $detail){
        if(!$request->filled('department_id')){
            return $this->failed('请输入部门id',201);
        }
        $department = $detail->find($request->id);
        $department->department_id = $request->department_id;
        $department->save();
        return $this->success('更新成功');
    }

    //更新子账号部门
    public function updateSubAccountDepartment($shop){
        if($shop->subAccounts && count($shop->subAccounts)){
            foreach ($shop->subAccounts as $subAccount){
                if($subAccount->department2_id!=$shop->department_two_id){
                    $subAccount->department1_id=$shop->department_one_id??'';
                    $subAccount->department2_id=$shop->department_two_id??'';
                    $subAccount->department3_id=null;
                    $subAccount->department_id=$shop->department_two_id??'';
                    $subAccount->save();
                    SubAccountStaffBind::where('sub_account_id',$subAccount->id)->delete();
                }
            }
        }
    }

    /**
     * 分配客服
     */
    public function distribution(ShopDetail $model,Request $request){
        $user = $request->user();
        $data = $model->find($request->id);
        $map = $request->except('shop');
        $data->update($map);
        //分配客服记录
        $this->fetchCustomerService($request,$user);
        return $this->success('分配成功!');
    }
    //设置未读信息
    protected function fetchCustomerService($request,$user){
        $users = SystemUser::query()->where('id','>',0)->pluck('id');
        $map = [];
        foreach ($users as $k=>$v){
            $map[$k]['shop_manage_id'] = $request->id;
            $map[$k]['user_id'] = $v;
            $map[$k]['department_one_id'] = $request->department_one_id;
            $map[$k]['department_two_id'] = $request->department_two_id;
            $map[$k]['department_three_id'] = $request->department_three_id;
            $map[$k]['operator_name'] = $user->name;
            $map[$k]['operator_department'] = $this->getDepartment($user->department_id);
            $map[$k]['operator_time'] = time();
        }
        DB::table('shop_records')->insert($map);
    }
    public function destory(ShopDetail $model,Request $request){
        $data = $model->find($request->id);
        $data->delete();
    }
    //终止店铺
    public function finalShop(ShopDetail $model,Request $request){
        $shop=$model->find($request->id);
        if($shop){
            $updateData=[
                'cooperation_status'=>2,
                'breakup_time'=>date('Y-m-d H:i:s'),
            ];
            $shop->update($updateData);
            $this->updateSubAccountStatus($shop);
        }
        return $this->success('终止成功');
    }
    //终止店铺下的子账号
    public function updateSubAccountStatus($shop){
        if($shop->subAccounts && count($shop->subAccounts)){
            foreach ($shop->subAccounts as $subAccount){
                if($subAccount->status==1){
                    $subAccount->status=0;
                    $subAccount->breakup_time=date('Y-m-d H:i:s');
                    $subAccount->save();
                }
            }
        }
    }

    //店铺资料记录列表
    public function RecordList(ShopRecord $model,Request $request){
        $shop_id = $request->filled('shop_id','');
        if(!$shop_id){
            return $this->failed('店铺id不能为空',201);
        }
        $model = $model->where('shop_manage_id',$shop_id)->get();
    }
    //获取是否有未读消息列表
    public function checkUpdate(ShopRecord $model,Request $request){
        $user = $request->user();
        $data = $model->where('shop_manage_id',$request->shop_manage_id)
            ->where('user_id',$user->id)
            ->where('is_read',1)
            ->get();
        if($data){
            return $this->success($data);
        }else{
            return $this->success('');
        }
    }
    //设置未读变成已读消息
    public function setRead(ShopRecord $model,Request $request){
        $user = $request->user();
        $model->where('shop_manage_id',$request->shop_manage_id)
            ->where('user_id',$user->id)
            ->update(['is_read'=>2]);
        return $this->success('更新成功');
    }
    //设置未读信息
    protected function setUnreadMessage($shop_id,$shop_materials,$user,$data){
        $users = $this->getUnreadUser($shop_id);
        if($users){
            $map = [];
            $time = time();
            foreach ($users as $k=>$v){
                $map[$k]['shop_manage_id'] = $shop_id;
                $map[$k]['user_id'] = $v;
                $map[$k]['shop_materials'] = $shop_materials;
                $map[$k]['operator_name'] = $user->name;
                $map[$k]['operator_department'] = $this->getDepartment($user->department_id);
                $map[$k]['operator_time'] = $time;
                $map[$k]['department_id'] = $data->department_id;
                $map[$k]['department_one_id'] = $data->department_one_id;
                $map[$k]['department_two_id'] = $data->department_two_id;
                $map[$k]['department_three_id'] = $data->department_three_id;

            }

            $record['shop_manage_id'] = $shop_id;
            $record['user_id'] = 1;
            $record['shop_materials'] = $shop_materials;
            $record['operator_name'] = $user->name;
            $record['operator_department'] = $this->getDepartment($user->department_id);
            $record['operator_time'] = $time;

            $record['department_id'] = $data->department_id;
            $record['department_one_id'] = $data->department_one_id;
            $record['department_two_id'] = $data->department_two_id;
            $record['department_three_id'] = $data->department_three_id;


            ShopUpdateHistory::query()->create($record);
            DB::table('shop_records')->insert($map);
        }

    }
    //获取部门相关信息
    protected function getDepartment($id){
        if($id>0){
            return Department::query()->where('id',$id)->value('name');
        }
        return '';
    }
    /*
     * 获取历史记录
     */
    public function getHistory(Request $request){
        $shop = ShopRecord::query()
            ->with('first','two','three')
            ->where('shop_manage_id',$request->id)->groupBy('operator_time')->paginate(10);
        foreach ($shop as &$v){
            $v['un_read_num'] = $this->getUnread($v->shop_manage_id,$v->operator_time,new ShopRecord());
        }
        unset($v);
        $short = ShortCutRecord::query()->where('shop_manage_id',$request->id)->groupBy('operator_time')->paginate(10);
        foreach ($short as &$v){
            $v['un_read_num'] = $this->getUnread($v->shop_manage_id,$v->operator_time,new ShortCutRecord());
        }
        unset($v);
        $shop_keeper = ShopKeeperRecord::query()->where('shop_manage_id',$request->id)->groupBy('operator_time')->paginate(10);
        foreach ($shop_keeper as &$v){
            $v['un_read_num'] = $this->getUnread($v->shop_manage_id,$v->operator_time,new ShopKeeperRecord());
        }
        unset($v);
        $train_material = TrainMaterialRecord::query()->where('shop_manage_id',$request->id)->groupBy('operator_time')->paginate(10);
        foreach ($train_material as &$v){
            $v['un_read_num'] = $this->getUnread($v->shop_manage_id,$v->operator_time,new TrainMaterialRecord());
        }
        unset($v);
        $customer_complaint = CustomerComplaintRecord::query()->where('shop_manage_id',$request->id)->groupBy('operator_time')->paginate(10);
        foreach ($customer_complaint as &$v){
            $v['un_read_num'] = $this->getUnread($v->shop_manage_id,$v->operator_time,new CustomerComplaintRecord());
        }
        unset($v);
        return $this->success(compact('shop','short','shop_keeper','train_material','customer_complaint'));
    }

    protected function getUnread($shop_id,$time,$model){
        return $model
            ->where('shop_manage_id',$shop_id)
            ->where('is_read',1)
            ->where('operator_time',$time)
            ->count();
    }
    //获取未读列表
    public function getUnreadList(Request $request){
        $size = $request->input('size',10);
        if($request->type==1){
            $model = ShopRecord::query();
        }elseif($request->type==2){
            $model = ShortCutRecord::query();
        }elseif($request->type==3){
            $model = ShopKeeperRecord::query();
        }elseif($request->type==4){
            $model = TrainMaterialRecord::query();
        }elseif($request->type==5){
            $model = CustomerComplaintRecord::query();
        }
        $data = $model->with(['user'=>function($query){
            $query->with('first','two','three')->select('id','name','department_one_id','department_two_id','department_three_id');
        }])
            ->where('shop_manage_id',$request->id)
            ->where('is_read',1)
            ->where('operator_time',$request->operator_time)
            ->paginate($size);
        return $this->success($data);
    }
}
